from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponseRedirect
from models import OrderedModel, GroupedOrderedModel
from django.db import transaction

@staff_member_required
@transaction.commit_on_success
def admin_move_ordered_model(request, direction, model_type_id, model_id):    
    ModelClass = ContentType.objects.get(id=model_type_id).model_class()
    
    if issubclass(ModelClass, OrderedModel):
        ordering_model = OrderedModel
    elif issubclass(ModelClass, GroupedOrderedModel):
        ordering_model = GroupedOrderedModel
    else:
        raise Exception("Invalid Model")
    
    if direction == "up":
        ordering_model.move_up(model_type_id, model_id)
    elif direction == "top":
        ordering_model.move_top(model_type_id, model_id)
    elif direction == "bottom":
        ordering_model.move_bottom(model_type_id, model_id)
    else:
        ordering_model.move_down(model_type_id, model_id)
    
    app_label = ModelClass._meta.app_label
    model_name = ModelClass.__name__.lower()
    query = request.META['HTTP_REFERER']
    query = query[query.rfind('?'):]
    url = "/admin/%s/%s/%s" % (app_label, model_name, query)
    return HttpResponseRedirect(url)